package org.openotdr.server;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.miyake.xml.MyXmlParser;
import com.miyake.xml.Parameter;

public class SearchServlet extends HttpServlet implements Servlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 725038434532313373L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		MyXmlParser parser = new MyXmlParser();
		parser.setName("OTDR Event Search");
		parser.setDescription("Anritsu OTDR Event Search Service");
		parser.getParameters().add(new Parameter("Splice", "Splice Loss Threshold", "Numeric", "0.1", "dB"));
		parser.getParameters().add(new Parameter("Reflect", "Reflect Threshold", "Numeric", "0.1", "dB"));
		parser.getParameters().add(new Parameter("End", "End Threshold", "Numeric", "0.1", "dB"));
		Parameter p = new Parameter("AutoPon", "Auto PON Mode", "Selection", "", "");
		p.getSelection().add("On");
		p.getSelection().add("Off");
		parser.getParameters().add(p);

		parser.setProvider("OpenOtdrProject");
		parser.setVersion("1.00");
		parser.setLicense("Free");
		resp.getWriter().print(parser.encode());
		resp.getWriter().flush();
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		MyXmlParser parser = new MyXmlParser();
		MyXmlParser out = new MyXmlParser();
		parser.decode(req.getInputStream());
		
//		parser.clear();
		
		String[] title = new String[5];
		title[0] = "No.";
		title[1] = "Distance";
		title[2] = "Type";
		title[3] = "Loss";
		title[4] = "Reflectance";
		
		{
			String[] y = new String[5];
			for (int i = 0; i < 5; i++) {
				y[i] = String.valueOf(i+1);
			}
			out.addY(y, title[0]);
		}
		{
			String[] y = new String[5];
			for (int i = 0; i < 5; i++) {
				y[i] = String.valueOf(i*20.43+10);
			}
			out.addY(y, title[1]);
		}
		{
			String[] y = new String[5];
			y[0] = "Splice";
			y[1] = "Splice";
			y[2] = "Reflect";
			y[3] = "Splice";
			y[4] = "End";
			out.addY(y, title[2]);	
		}
		{
			String[] y = new String[5];
			for (int i = 0; i < 5; i++) {
				y[i] = String.format("%.5e", Math.random());
			}
			out.addY(y, title[3]);
		}
		{
			String[] y = new String[5];
			for (int i = 0; i < 5; i++) {
				y[i] = String.format("%.5e", Math.random());
			}
			out.addY(y, title[4]);
		}
		out.setName("Event Table");
		out.setLength(5);
		for (Parameter p : parser.getParameters()) {
			out.getParameters().add(p);
		}

		resp.getWriter().print(out.encode());
		resp.getWriter().flush();
		resp.getWriter().close();
	}
}
